import Vue from 'vue';
import Vuex from 'vuex';

import {
  INCREMENT
} from "./mutations-types"

// 安装插件
Vue.use(Vuex);

// 模块
const moduleA = {
  state: {
    name: 'hanxiao'
  },
  mutations: {
    updateName(state, payload) {
      state.name = payload;
    }
  },
  actions: {
    // context只针对本模块
    aUpdateName(context) {
      new Promise((resolve, reject) => {
        setTimeout(() => {
          context.commit('updateName', 'songyuan');
        }, 1000);    
      });
    }
  },
  getters: {
    fullName(state) {
      return state.name + 'beijin';
    },
    fullName2(state, getters) {
      return getters.fullName + 'baijing';
    },
    fullName3(state, getters, rootState) {
      return getters.fullName2 + rootState.counter;
    }
  }
}

// 创建对象
const store = new Vuex.Store({
  state: {
    counter: 1000,
    students: [
      {id: 110, name: 'xmo', age:20},
      {id: 111, name: 'zhaoyi', age:20},
      {id: 112, name: 'xumo', age:17},
      {id: 113, name: 'duming', age:19},      
    ],
    info: {
      name: 'yangchen',
      age: 30,
      height: 1.78
    }
  },
  mutations: {
    // 方法
    // 默认参数state，用于获取state中数据

    // 统一式写法
    [INCREMENT](state) {
      state.counter ++;
    },
    decrement(state) {
      state.counter --;
    },
    incrementCount(state, count) {
      state.counter += count;
    },
    incrementCountSpecial(state, payload) {
      state.counter += payload.count;
    },
    // 多个参数用对象传递
    addStudent(state, student) {
      state.students.push(student);
    },
    updateInfo(state) {
      // state.info.name = "lina";

      // 添加的新属性无法提供响应
      // state.info['address'] = 'chuyunshangu';

      // 如果需要提供响应，请使用push / pop / set
      // Vue.set(state.info, 'address', 'chuyunshangu');

      // 删除属性 delete
      // Vue.delete(state.info, 'age');

      // 不推荐使用异步操作，会无法追踪，必须使用Action
      state.info.name = "lina";        
    }
  },
  actions: {
    // 默认参数context，即store对象
    // 额外参数payload
    aUpdateInfo(context, payload) {
      // setTimeout(() => {
      //   // 不能这么做，仍然必须使用mutation
      //   // context.state.info.name = "lina";
      //   context.commit('updateInfo');
      //   // console.log(payload.message);
      //   // payload.success();

      //   console.log(payload);
      // }, 1000);

      // resolve会执行最近的then函数，即便不在一个文件内
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          context.commit('updateInfo');
          console.log(payload);
          resolve("succeed");
        }, 1000);
      });
    }
  },
  // 相当于计算属性
  // 默认参数state
  getters: {
    powerCounter(state) {
      return state.counter**2;
    },
    beyond20(state) {
      return state.students.filter(i => i.age >= 20);
    },
    // 第二个默认参数getters
    beyond20Len(state, getters) {
      return getters.beyond20.length;
    },
    beyondXStu(state) {
      return x => state.students.filter(i => i.age >= x);
    }
  },
  modules: {
    a: moduleA
  }
});

export default store;